<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Feedback;
use App\Model\Message;
use App\Model\Role;
use App\Model\User;
use App\Model\UserRole;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class UserController extends AbstractController
{

    #[GetMapping(path: '/sys/user')]
    public function list()
    {
        $nickname = $this->request->input('nickname', '');
        $loginType = $this->request->input('loginType', '');
        $status = $this->request->input('status', '');
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $user_id = Context::get('uid');
        $list = User::query()
            ->where('id', '<>', $user_id)
            ->when($nickname, function ($query, $nickname) {
                $query->where('nickname', 'like', '%' . $nickname . '%');
            })
            ->when($loginType, function ($query, $loginType) {
                $query->where('login_type', $loginType);
            })
            ->when($status, function ($query, $status) {
                $query->where('status', $status);
            })
            ->select('id', 'username', 'sex', 'mobile', 'email', 'nickname', 'avatar', 'ip', 'ip_location as ipLocation', 'status', 'login_type as loginType', 'last_login_time as lastLoginTime', 'create_time as createTime', 'update_time as updateTime')
            ->with(['roles'])
            ->get();
        $data['searchCount'] = true;
        $data['current'] = (int)$pageNum;
        $data['size'] = (int)$pageSize;
        $data['total'] = User::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        foreach ($list as &$item) {
            $item['roleIds'] = $item->roles->pluck('id');
            unset($item['roles']);
        }
        $data['records'] = $list;
        return success($data);
    }

    #[RequestMapping(path: '/sys/user', methods: ['PUT', 'POST'])]
    public function update()
    {
        $user = $this->request->input('user');
        $roleIds = $this->request->input('roleIds');
        try {
            Db::beginTransaction();
            if (!isset($user['id'])) {
                $user['login_type'] = $user['loginType'];
                unset($user['loginType']);
                unset($user['roleIds']);
                $user = User::query()->create($user);
            } else {
                User::query()->where('id', $user['id'])->update([
                    'nickname' => $user['nickname'],
                    'sex' => $user['sex'],
                    'mobile' => $user['mobile'],
                    'email' => $user['email'],
                    'status' => $user['status'],
                ]);
                UserRole::query()->where('user_id', $user['id'])->delete();
            }
            if (!empty($roleIds)) {
                foreach ($roleIds as $roleId) {
                    UserRole::query()->create([
                        'user_id' => $user['id'],
                        'role_id' => $roleId,
                    ]);
                }
            }
            Db::commit();
            return success();
        } catch (\Throwable $e) {
            Db::rollBack();
            logInfo('delete', $e->getMessage(), 'user');
            return fail(201, $e->getMessage());
        }
    }

    #[DeleteMapping(path: '/sys/user/delete/{ids}')]
    public function delete($ids)
    {
        try {
            $idArr = explode(',', $ids);
            Db::beginTransaction();
            foreach ($idArr as $id) {
                $user = User::query()->where('id', $id)->first();
                if ($user) {
                    User::query()->where('id', $id)->delete();
                    UserRole::query()->where('user_id', $user['id'])->delete();
                }
            }
            Db::commit();
            return success();
        } catch (\Throwable $e) {
            Db::rollBack();
            logInfo('delete', $e->getMessage(), 'user');
            return fail(201, $e->getMessage());
        }

    }

    #[GetMapping(path: '/sys/user/profile')]
    public function profile()
    {
        $user_id = Context::get('uid');
        $user = User::query()->where('id', $user_id)->first();
        return success(['sysUser' => $user]);
    }

    #[PutMapping(path: '/sys/user/reset')]
    public function reset()
    {
        $id = $this->request->input('id');
        $newPassword = $this->request->input('password');
        User::query()->where('id', $id)->update(['password' => $newPassword]);
        return success();
    }

    #[PutMapping(path: '/sys/user/updatePwd')]
    public function updatePwd()
    {
        $user_id = Context::get('uid');
        $confirmPassword = $this->request->input('confirmPassword');
        $newPassword = $this->request->input('newPassword');
        $oldPassword = $this->request->input('oldPassword');
        $user = User::query()->where('id', $user_id)->first();
        if ($newPassword != $confirmPassword) {
            return fail(201, '两次密码不一致');
        }
        if ($user->password != $oldPassword) {
            return fail(201, '当前密码错误');
        }
        User::query()->where('id', $user_id)->update(['password' => $newPassword]);
        return success();
    }


}
